//
//  ReportLearnViewController.m
//  LoveDraw
//
//  Created by 零零壹 on 2017/7/17.
//  Copyright © 2017年 梁晨. All rights reserved.
//

#import "ReportLearnViewController.h"
#import "ReportLearnCollectionViewCell.h"
#import "PlaceholderTextView.h"
#import "JFImagePickerController.h"
#import "PopWindowView.h"

@interface ReportLearnViewController ()<JFImagePickerDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
{
    NSMutableArray *photos;
    UICollectionView *photosList;
}

@property(nonatomic,strong)UIScrollView *scrV;
@property(nonatomic,strong)PlaceholderTextView *TextV;
@property(nonatomic,strong)UICollectionView *MuBanCollectV;
@property(nonatomic,strong)NSMutableArray *MuBanlistArr;
@property(nonatomic,strong)UIButton *Commit;

@end

@implementation ReportLearnViewController

-(UIButton *)Commit
{
    if (!_Commit) {
        _Commit = [UIButton buttonWithType:(UIButtonTypeSystem)];
        [_Commit setTitle:@"确定" forState:(UIControlStateNormal)];
        [_Commit addTarget:self action:@selector(CommitAct) forControlEvents:(UIControlEventTouchUpInside)];

        _Commit.layer.masksToBounds = YES;
        _Commit.layer.cornerRadius = 5;

        [_Commit setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        _Commit.backgroundColor = UIColors(MainColor);
    }
    return _Commit;
}

-(NSMutableArray *)MuBanlistArr
{
    if (!_MuBanlistArr) {
        _MuBanlistArr = [NSMutableArray array];
    }
    return _MuBanlistArr;
}

-(UIScrollView *)scrV
{
    if (!_scrV)
    {
        _scrV = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, KscreenW, KscreenH)];
        _scrV.bounces = NO;
    }
    return _scrV;
}

-(PlaceholderTextView *)TextV
{
    if (!_TextV) {
        _TextV = [[PlaceholderTextView alloc]initWithFrame:CGRectMake(15, 10, KscreenW-30, 200*KscreenH/667)];
        _TextV.layer.masksToBounds = YES;
        _TextV.layer.cornerRadius = 5;
        _TextV.layer.borderWidth = 1;
        _TextV.layer.borderColor = UIColors(0xEFEFEF).CGColor;
        _TextV.placeholder = @"请输入要说的话";
    }
    return _TextV;
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = @"学习小结";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.scrV];
    [self.scrV addSubview:self.TextV];
    [self CreateMuBan];
    [self CreateRightBtn];
    [self getMubanList];
    photos = [[NSMutableArray alloc] init];

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 5;
    NSInteger size = (MAIN_SCREEN_WIDTH-40)/5;
    if (size%2!=0) {
        size-=1;
    }
    flowLayout.itemSize = CGSizeMake(size, size);
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);

    photosList = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:flowLayout];
    photosList.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    photosList.scrollIndicatorInsets = photosList.contentInset;
    photosList.delegate = self;
    photosList.dataSource = self;
    photosList.backgroundColor = [UIColor clearColor];
    photosList.alwaysBounceVertical = YES;

    [self.view addSubview:photosList];
    [photosList registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"imagePickerCell"];
//    photosList.backgroundColor = [UIColor redColor];
    photosList.scrollEnabled = NO;

    [photosList mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.top.equalTo(self.MuBanCollectV.mas_bottom).offset(10);
        make.height.mas_equalTo(160);
    }];

    [self.view addSubview:self.Commit];
}

-(void)CreateMuBan
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.minimumLineSpacing = 10;
    layout.minimumLineSpacing = 15;
    layout.itemSize = CGSizeMake((KscreenW-50)/3,40);
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);

    self.MuBanCollectV = [[UICollectionView alloc]initWithFrame:CGRectMake(15, 200*KscreenH/667+20, KscreenW-30, 100) collectionViewLayout:layout];
    self.MuBanCollectV.backgroundColor = [UIColor whiteColor];
    self.MuBanCollectV.delegate = self;
    self.MuBanCollectV.dataSource = self;
    [self.MuBanCollectV registerNib:[UINib nibWithNibName:@"ReportLearnCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ReportLearnCollectionViewCell"];
    [self.scrV addSubview:self.MuBanCollectV];
}

-(void)CreateRightBtn
{
    UIButton *rightBtn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [rightBtn setTitle:@"保存模板" forState:(UIControlStateNormal)];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    rightBtn.frame = CGRectMake(0, 0, 80, 60);
    [rightBtn addTarget:self action:@selector(RightBtnAct) forControlEvents:(UIControlEventTouchUpInside)];
    UIBarButtonItem *rightbarBtn = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightbarBtn;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == self.MuBanCollectV) {
         return self.MuBanlistArr.count;
    }else
    {
        if(photos.count==0){
            return 1;
        }else{
            return photos.count+1;
        }
    }
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.MuBanCollectV) {
        NSDictionary *mubandDic = self.MuBanlistArr[indexPath.row];
        ReportLearnCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ReportLearnCollectionViewCell" forIndexPath:indexPath];
        cell.title.text = mubandDic[@"title"];
        return cell;
    }else
    {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imagePickerCell" forIndexPath:indexPath];

        if(photos.count==indexPath.row){
            UIImageView *imgView = (UIImageView *)[cell.contentView viewWithTag:1];
            if (!imgView) {
                imgView = [[UIImageView alloc] initWithFrame:cell.bounds];
                imgView.contentMode = UIViewContentModeScaleAspectFill;
                imgView.clipsToBounds = YES;
                imgView.tag = 1;
                [cell addSubview:imgView];
            }
            [imgView setImage:[UIImage imageNamed:@"upload"]];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(upladImage:)];
            [cell addGestureRecognizer:tap];
        }else{
            ALAsset *asset = photos[indexPath.row];
            UIImageView *imgView = (UIImageView *)[cell.contentView viewWithTag:1];
            if (!imgView) {
                imgView = [[UIImageView alloc] initWithFrame:cell.bounds];
                imgView.contentMode = UIViewContentModeScaleAspectFill;
                imgView.clipsToBounds = YES;
                imgView.tag = 1;
                [cell addSubview:imgView];
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(preview:)];
                [cell addGestureRecognizer:tap];
            }
            cell.tag = indexPath.item;

            [[JFImageManager sharedManager] thumbWithAsset:asset resultHandler:^(UIImage *result) {
                if (cell.tag==indexPath.item)
                {
                    //  NSData *data = UIImageJPEGRepresentation(result, 1);
                    imgView.image = result;
                }
            }];
        }
        return cell;
    }
}

-(void)upladImage:(UITapGestureRecognizer *)tap{
    JFImagePickerController *picker = [[JFImagePickerController alloc] initWithRootViewController:nil];
    picker.pickerDelegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)preview:(UITapGestureRecognizer *)tap{
    UIView *temp = tap.view;
    JFImagePickerController *picker = [[JFImagePickerController alloc] initWithPreviewIndex:temp.tag];
    picker.pickerDelegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}
- (void)imagePickerDidFinished:(JFImagePickerController *)picker{
    [photos removeAllObjects];
    [photos addObjectsFromArray:picker.assets];

    [photosList reloadData];
    [self imagePickerDidCancel:picker];
}

- (void)imagePickerDidCancel:(JFImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.MuBanCollectV) {
        ReportLearnCollectionViewCell *cell = (ReportLearnCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
        cell.title.textColor = UIColors(MainColor);
        cell.title.layer.borderColor = UIColors(MainColor).CGColor;
        self.TextV.placeholder = @"";
        NSDictionary *mubandDic = self.MuBanlistArr[indexPath.row];
        self.TextV.text= mubandDic[@"contents"];
    }else
    {

    }
}

-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.MuBanCollectV == collectionView) {
        ReportLearnCollectionViewCell *cell = (ReportLearnCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
        cell.title.textColor = UIColors(0x666666);
        cell.title.layer.borderColor = UIColors(0xEFEFEF).CGColor;
    }else
    {

    }
}


-(void)RightBtnAct
{
    if (self.TextV.text.length == 0)
    {
        [HUD showText:@"内容不能为空" AfterTime:1];
    }else
    {
        PopWindowView *poppicker = [[PopWindowView alloc]initWithCompleteBlock:^(NSString *conText)
                                    {
                                        [self upMuBantitle:conText];
                                    }];
        poppicker.themeColor = [UIColor blueColor];
        poppicker.title        = @"模板名称";
        poppicker.placehoder   = @"请输入模板名称";
        poppicker.themeColor   =  UIColors(MainColor);
        [poppicker show];
    }
}

-(void)upMuBantitle:(NSString *)title
{

    [RequestManager HudRequestWithUrl:@"/index.php?g=App&m=TeacherCourserep&a=addSummarytemplate" parmDic:@{@"title":title,@"contents":self.TextV.text} requestType:RequestPOST view:self.view Success:^(id data)
    {
        [self.MuBanCollectV reloadData];
    } error:^(NSError *error) {

    }];
}

-(void)getMubanList
{
    [RequestManager RequstWithUrl:@"/index.php?g=App&m=TeacherCourserep&a=summaryTemplate" parmDic:@{} requestType:RequestPOST Success:^(id data)
    {
        self.MuBanlistArr = data;
        NSLog(@"%ld",self.MuBanlistArr.count);

        self.MuBanCollectV.frame = CGRectMake(15, 200*KscreenH/667+20, KscreenW-30, self.MuBanlistArr.count/3.0*60);
        [self.MuBanCollectV reloadData];

//        .frame = CGRectMake(10, KscreenH-60-64, KscreenW-20, 50);
        [self.Commit mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.scrV.mas_left);
            make.width.mas_equalTo(KscreenW);
            make.height.mas_equalTo(45);
            make.top.equalTo(photosList.mas_bottom).offset(5);
//            make.bottom.equalTo(self.scrV.mas_bottom).offset(-10);
        }];


    } error:^(NSError *error) {

    }];
}

/**
 提交的方法
 */
-(void)CommitAct
{
    dispatch_queue_t queue = dispatch_queue_create("upimage", DISPATCH_QUEUE_CONCURRENT);
    dispatch_sync(queue, ^{
        if (photos.count==0)
        {
            NSString *content = self.TextV.text;
            [self DopostAllinfo:content arr:[@[] mutableCopy]];
        }else
        {
            NSString *content = self.TextV.text;
            NSMutableArray *indexArr = [@[]mutableCopy];
            for (NSInteger i = 0; i < photos.count; i++)
            {
                ALAsset *asset = photos[i];
                UIImage *upimage = [ASSETHELPER getImageFromAsset:asset type:ASSET_PHOTO_FULL_RESOLUTION];
                

                [[UploadImage sharedClient]doUploadImage:@"/index.php?g=App&m=Index&a=uploadsImgone" parameters:@{@"uid":[[NSUserDefaults standardUserDefaults]objectForKey:kUserId],@"access_token":[[NSUserDefaults standardUserDefaults]objectForKey:kAccessToken]} image:upimage successBlock:^(id responseBody)
                 {
                     NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseBody options:0 error:nil];
                     if ([dic[@"flag"]isEqualToString:@"Success"]) {
                         NSDictionary *imageAndIndexDic = @{@"index":[NSString stringWithFormat:@"%ld",i],@"imageUrl":dic[@"data"]};

                         [indexArr addObject:imageAndIndexDic];

                         if (indexArr.count == photos.count)
                         {
                             [self DopostAllinfo:content arr:indexArr];
                         }
                     }else
                     {
                         [HUD showText:dic[@"Success"] AfterTime:1];
                     }
                 } failureBlock:^(NSString *error)
                 {
                 }];
            }
        }
    });
}

-(void)DopostAllinfo:(NSString *)content arr:(NSMutableArray *)imageArr
{
    NSMutableArray *uploadArr = [NSMutableArray array];

    if (imageArr.count == 0)
    {
        
    }else
    {
        for (NSInteger i = 0 ; i<imageArr.count-1; i++)
        {
            for (NSInteger j = 0; j<imageArr.count-1-i; j++)
            {
                if ([imageArr[j][@"index"] intValue]>[imageArr[i][@"index"] intValue]) {
                    NSDictionary *dic = imageArr[j];
                    imageArr[j] =imageArr[j+1];
                    imageArr[j+1] = dic;
                }
            }
        }
    }

    for (NSDictionary *dic in imageArr) {
        [uploadArr addObject:dic[@"imageUrl"]];
    }

    [RequestManager HudRequestWithUrl:@"/index.php?g=App&m=TeacherCourserep&a=addCoursereport" parmDic:@{@"tid":[[NSUserDefaults standardUserDefaults]objectForKey:@"tid"],@"caid":self.model.aid,@"sid":self.model.sid,@"name":self.model.name,@"contents":content,@"thumbs":uploadArr} requestType:RequestPOST view:self.view Success:^(id data)
    {
        [self.navigationController popViewControllerAnimated:YES];
    } error:^(NSError *error) {

    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
